package com.emm.yixun.customer.service.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.basic.mapper.BaseCodeValueMapper;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.DialTransactionalService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.FollowService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.NoticeTemporaryService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.Follow;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.FollowDto;
import com.emm.yixun.common.model.dto.MessageReceiverDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.NoticeTemporaryDto;
import com.emm.yixun.common.model.dto.TelRecordDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.CustomerSexEnum;
import com.emm.yixun.common.model.enums.CustomerStarEnum;
import com.emm.yixun.common.model.enums.CustomerStatusEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IntentionLevelEnum;
import com.emm.yixun.common.model.enums.IsReadEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.IsValidEnum;
import com.emm.yixun.common.model.enums.NoticeTypeEnum;
import com.emm.yixun.common.model.enums.ReceiveStatusEnum;
import com.emm.yixun.customer.service.FollowServiceFacade;

@Service("followServiceFacade")
@WebService(name="com.emm.yixun.customer.service.FollowServiceFacade")
public class FollowServiceFacadeImpl implements FollowServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private FollowService followService;
	
	@Autowired
	private DataPermissionService dataPermissionService;
	
	@Autowired
	private DialTransactionalService dialTransactionalService;
	
	@Autowired
	private NoticeTemporaryService noticeTemporaryService;
	
	@Autowired
	private MessageReceiverService messageReceiverService;
	
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private NoticeService noticeService;
	
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private BaseCodeValueMapper baseCodeValueMapper;
	

	@Override
	public Response<FollowDto> save(FollowDto dto) {
		Response<FollowDto> response=new Response<FollowDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			FollowDto mDto=followService.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(FollowDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=followService.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			FollowDto mDto=new FollowDto();
			mDto.setId(id);
			int count=followService.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<Follow> findById(Long id) {
		Response<Follow> response=new Response<Follow>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Follow entity=followService.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<Follow> findByDto(FollowDto dto) {
		ResponseList<Follow> response=new ResponseList<Follow>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Follow> list=followService.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<Follow> findPageByDto(FollowDto dto, Integer begin,Integer row) {
		Page<Follow> response=new Page<Follow>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Follow> page = followService.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public Response<Page<FollowDto>> getFollowList(FollowDto reqDto, Integer pageSize, Integer pageNum) {
		if (StringUtils.isNotBlank(reqDto.getFollowModes())) {
			String sql = new String(" and t.follow_mode in (");
			String[] audits = reqDto.getFollowModes().split(",");
			String sbsql = "";
			for (int i = 0; i < audits.length; i++) {
				sbsql += audits[i];
				if (i != audits.length - 1) {
					sbsql += ",";
				}
			}
			sql += sbsql + ")";
			reqDto.setFollowModes(sql);
		}else{
			reqDto.setFollowModes(" and t.follow_mode != '6'");
		}
		//数据权限
		Response<Page<FollowDto>> resDto = new Response<Page<FollowDto>>();
		if(SysConstants.openDataPermission){
			String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(), reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
			String [] dataPermissionArr = dataPermission.split(":");
			if("00".equals(dataPermissionArr[0])){
				resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
				resDto.setSuccess(false);
				return resDto;
			}
			reqDto.setDataPermission(dataPermissionArr[1]);
		}
		
		try {
			Page<FollowDto> payDepositPage = followService.getFollowDtoList(reqDto,
					PageUtil.begin(pageNum, pageSize), pageSize);
			payDepositPage.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(payDepositPage);
			return resDto;
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	@Override
	public ResponseList<Project> findProjectByDto(FollowDto entity) {
		ResponseList<Project> response=new ResponseList<Project>();
		try {
			if(null==entity){
				response.setSuccess(false);
				return response;
			}
			
			//数据权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(), entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
				String [] dataPermissionArr = dataPermission.split(":");
				if("00".equals(dataPermissionArr[0])){
					response.setSuccess(false);
					return response;
				}
				entity.setDataPermission(dataPermissionArr[1]);
			}
			
			List<Project> list=followService.selectFollowProject(entity);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
	
	public Response<FollowDto> callAndFollow(TelRecordDto trd,FollowDto fd){
		Response<FollowDto> fdResponse= new Response<FollowDto>();
		try {
			FollowDto followDto= dialTransactionalService.callAndFollow(trd, fd);
			fdResponse.success(followDto);
		} catch (Exception e) {
			fdResponse.fail("0000", "拨打电话并生成跟进记录出错");
			logger.error("拨打电话并生成跟进记录出错：{}",e);
		}
		return fdResponse;
	}
	
	@SuppressWarnings("null")
	@Override
	public Response<CommonResDTO> customerFollowPushMsg() {
		Response<CommonResDTO> response = new Response<CommonResDTO>();
		CommonResDTO resDto = new CommonResDTO();
		resDto.setResult("0");
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
			Date beforeDate = dateCalendar(Calendar.DATE, new Date(), -1);
			Date afertDate = dateCalendar(Calendar.DATE, new Date(), 1);
			
			FollowDto entity = new FollowDto();
			entity.setNextFollowTimeBefore(sdf.format(beforeDate));
			entity.setNextFollowTimeAfter(sdf.format(afertDate));
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<Follow> list = followService.selectListByDto(entity);
			if(list == null && list.size() <= 0){
				logger.error("推送跟进提醒失败：{}","未设置模板");
				resDto.setErrorMsg("未设置模板");
				response.success(resDto);
			}
			
			DictionaryDto dto = new DictionaryDto();
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			dto.setDictionaryValue("NT46");
			Dictionary dic = dictionaryService.selectByDto(dto);
			if(dic == null){
				logger.error("推送跟进提醒失败：{}","未设置模板");
				resDto.setErrorMsg("未设置模板");
				response.setSuccess(false);
				return response;
			}
			
			for(int i = 0; i < list.size(); i++){
				Follow follow = (Follow)list.get(i);
				
				List<User> userList = new ArrayList<User>();
				Customer customer = customerService.selectById(follow.getCustomerId()); //查询客户姓名
				Project project = projectService.selectById(customer.getProjectId()); //查询项目名称
				User user = operateUser(customer.getUserCode());//查询归属人ID
				userList.add(user);
				String content = dic.getDictionaryName()
						.replace("${customer}", customer.getCustomerName())
						.replace("${content}", follow.getNextFollowContent());
				//保存推送临时表
				NoticeTemporaryDto notice = new NoticeTemporaryDto();
				notice.setTitle("下次跟进提醒");
				notice.setContent(content);
				notice.setReceiverId(user.getId());
				notice.setAction("下次跟进提醒");
				notice.setPushType("NT46");
				notice.setMerchantId(follow.getMerchantId());
				notice.setProjectName(project.getProjectName());
				notice.setProjectCode(project.getProjectCode());
				notice.setBusinessId(follow.getId()+"");
				notice.setDelFlag(DelFlagEnum.UNDEL.getNo());
				notice.setTempType("7");
				String remindCategory = queryCustomerEntity(customer, follow);
				notice.setRemindCategory(remindCategory);
   	 			noticeTemporaryService.create(notice);
   	 			
   	 			//组装消息数据
	   	 		Map<String, String> noticeParamMap = new HashMap<String, String>();
				noticeParamMap.put("noticeDicId", dic.getId()+"");
				noticeParamMap.put("noticeTempType", "NT46");
				noticeParamMap.put("sendMsg", content);
				noticeParamMap.put("title", "下次跟进提醒");
				noticeParamMap.put("merchantId", String.valueOf(customer.getMerchantId()));
				noticeParamMap.put("projectCode", customer.getProjectCode());
				noticeParamMap.put("userCode", customer.getUserCode());
				noticeParamMap.put("accessCode", customer.getAccessCode());
				noticeParamMap.put("createUserId", String.valueOf(follow.getCreateUserId()));
				noticeParamMap.put("businessId", follow.getId()+"");
				noticeParamMap.put("customerId", customer.getId()+"");
				
				Map<String,String> replaceValuesMap=new HashMap<String,String>();
				replaceValuesMap.put(MsgUtil.ROOM_ID, "");
				replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
				replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
				replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
				replaceValuesMap.put(MsgUtil.BUSINESS_ID, follow.getId()+"");
		    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
   	 			
		    	createNotice(noticeParamMap, user);
   	 			
			}
			resDto.setResult("1");
			response.success(resDto);
		} catch (Exception e) {
			logger.error("推送跟进提醒失败：{}",e);
			resDto.setErrorMsg("推送跟进提醒失败");
			response.setSuccess(false);
		}
		return response;
	}
	
	/**
	 * 获取归属人
	 * @param reqDto
	 * @return
	 */
	public User operateUser(String UserCode){
		User user = null;
		if (null != UserCode) {
			UserDto userDto = new UserDto();
			userDto.setUserCode(UserCode);
			user = userService.selectByDto(userDto);
		}
		return user;
	}
	
	/**
	 * 插入消息 
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO createNotice(Map<String, String> noticeParamMap, User user) {
		CommonResDTO resDto = new CommonResDTO();
		try{
			//生成消息,生成接收人信息
			NoticeDto noticeDto = new NoticeDto();
			//通知字典表中类型ID
			noticeDto.setDictionaryId(Long.parseLong(noticeParamMap.get("noticeDicId")));
			noticeDto.setNoticeType(NoticeTypeEnum.REMIND.getNo());
			noticeDto.setNoticeTempType(noticeParamMap.get("noticeTempType")); 
			noticeDto.setTitle(noticeParamMap.get("title"));
			noticeDto.setContent(noticeParamMap.get("sendMsg"));
			noticeDto.setIssueTime(Calendar.getInstance().getTime());
			if(noticeParamMap.get("timerNotice") != null){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				noticeDto.setTimerNotice(sdf.parse(noticeParamMap.get("timerNotice")));
			}
			noticeDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
			if(noticeParamMap.get("projectCode") != null){
				noticeDto.setProjectCode(noticeParamMap.get("projectCode"));
			}
			noticeDto.setUserCode(noticeParamMap.get("userCode"));
			noticeDto.setAccessCode(noticeParamMap.get("accessCode"));
			noticeDto.setIsValid(IsValidEnum.VALID.getNo());
			noticeDto.setIsRead(IsReadEnum.UNREAD.getNo());
			noticeDto.setIsSend(IsSendEnum.UNSEND.getNo());
			noticeDto.setCreateUserId(Long.parseLong(noticeParamMap.get("createUserId")));
			noticeDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			/*
			 * (ym) 提醒内容增加超链接 start
			 * */
			noticeDto.setRemark(noticeParamMap.get("replaceValues"));
			/*
			 * (ym) 提醒内容增加超链接 end
			 * */
			noticeDto = noticeService.create(noticeDto);
			
			//添加接收人
			MessageReceiverDto msgRecDto = new MessageReceiverDto();
			msgRecDto.setNoticeId(noticeDto.getId());
			msgRecDto.setReceiverId(user.getId());
			msgRecDto.setReceiveStatus(ReceiveStatusEnum.UNRECEIVED.getNo());
			msgRecDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
			msgRecDto.setCreateUserId(Long.parseLong(noticeParamMap.get("createUserId")));
			msgRecDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			msgRecDto.setUpdateTime(new Date());
			messageReceiverService.create(msgRecDto);
						
			resDto.setResult("1");
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("添加提醒消息失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
     * 计算XX时间前后的时间，例如 2小时前
     * @param type 时间类型  Calendar.HOUR，Calendar.MONTH...
     * @param time 日期
     * @param num 被加减数 
     * @return Date
     * @throws ParseException  
     */
    public static Date dateCalendar(int type, Date date, int num){
        Calendar now = Calendar.getInstance();  
        now.setTime(date);  
        now.set(type, now.get(type) + num);  
        return now.getTime();
    }
    
    /**
     * 组装下次跟进提醒字符串返回
     * @param customer
     * @param follow
     * @return
     */
    public String queryCustomerEntity(Customer customer, Follow follow){
    	String customerName = "";
    	String customerStar = "";
    	String intentionLevel = "";
    	String customerOrigin = "";
    	String customerStatus = "";
    	String mobile = "";
    	String customerSex = "";
    	//客户姓名
		if(StringUtils.isNotEmpty(customer.getCustomerName())){
			customerName = customer.getCustomerName();
		}
    	//星标
		if(StringUtils.isNotEmpty(customer.getCustomerStar())){
			customerStar = CustomerStarEnum.getByNo(customer.getCustomerStar()).getDes();
		}
    	//意向等级
		if(StringUtils.isNotEmpty(customer.getIntentionLevel())){
			intentionLevel = IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes();
		}
		//客户来源
		if(StringUtils.isNotEmpty(customer.getCustomerOrigin())){
			BaseCodeValue baseCodeValue = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCustomerOrigin()));
			if(baseCodeValue != null){
				customerOrigin = baseCodeValue.getCodeName();
			}
		}
		//客户状态
		if(StringUtils.isNotEmpty(customer.getCustomerStatus())){
			customerStatus = CustomerStatusEnum.getByNo(customer.getCustomerStatus()).getDes();
		}
		//电话
		if(StringUtils.isNotEmpty(customer.getPeMobile())){
			mobile = customer.getPeMobile();
		}
		//性别
		if(StringUtils.isNotEmpty(customer.getCustomerSex())){
			customerSex = CustomerSexEnum.getByNo(customer.getCustomerSex()).getDes();
		}
		//按移动端返回顺序组装字符串参数
		String remindCategory = follow.getId()+","+customerName+","+
					customerStar+","+intentionLevel+","+customerOrigin+","+customerStatus+","+mobile+","+customerSex;
    	return remindCategory;
    }

}
